package com.example.gustavo.hello.utils;

import android.text.TextUtils;

import java.text.DecimalFormat;

/**
 * 
 * @author gustavo
 * 2014年4月28日 17:30:45 	
 */
public class MathUtils {

    private static DecimalFormat df;

    /**
	 * 四舍五入,保留两位小数,带正负号
	 * @param number
	 * @return
	 */
	public static String toTwoWithFlag(String number){
		if(TextUtils.isEmpty(number)){
			return "";
		}
		double num = 0;
		try {
			num = Double.parseDouble(number);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		if(num >0){
			return "+"+toTwo(num);
		}else{
			return toTwo(num);
		}
	}
	public static String toTwoWithFlag(float number){
		if(number >0){
			return "+"+toTwo(number);
		}else{
			return toTwo(number);
		}
	}

	/**
	 * 四舍五入 保留两位小数
	 * @param number	double/float/int/long类型
	 * @return
	 */
	public static String toTwo(Object number){
		DecimalFormat df = new DecimalFormat("#0.00");//四舍五入 保留两位小数
		return df.format(number);
	}
	/**
	 * 四舍五入 保留两位小数
	 * @param number
	 * @return
	 */
	public static String toTwo(String number){
		if(TextUtils.isEmpty(number)){
			return "";
		}
		double num = 0;
		try {
			num = Double.parseDouble(number);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return toTwo(num);
	}
	/**
	 * 
	 * @param number
	 * @return
	 */
	public static String formatSize(double number){
        if(number == 0) return "0";

        String[] unit = {"","万","亿","万亿"};
        int index = 0;

        while(Math.abs(number) > 10000){
            number /= 10000;
            index++;
        }
        return toTwo(number)+ unit[index];
	}
	/**
	 * 将数据转换为xx万/xx亿
	 * @param number
	 * @return	String
	 */
	public static String formatSize(String number){
		if(TextUtils.isEmpty(number)){
			return "";
		}
		double num = 0;
		try {
			num = Double.parseDouble(number);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return formatSize(num);
	}


    /**
     *
     * @param value	需要格式化的数字
     * @param num	保留的小数位数
     * @return
     */
    public static String formatNumber(double value, int num) {
        String pattern = "#0";
        if(num >0){
            pattern += ".";
            for (int i = 0; i < num; i++) {
                pattern += "0";
            }
        }
        if (df == null) {
            df = new DecimalFormat(pattern);
        }
        return df.format(value);
    }
}
